package com.example.demo.service;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.Map;

/**
 * 限流接口
 *
 * @author zxb
 **/
public interface ILocalRateLimiter {

    /**
     * 是否允许通过
     *
     * @param key
     * @return true 放行，false 禁止访问（限流）
     */
    RateLimiterResponse access(Object key);

    /**
     * 限制的 key
     *
     * @param key
     * @return
     */
    String getLimitKey(Object key);

    @Data
    @Accessors(chain = true)
    class RateLimiterResponse {
        /**
         * 是否允许通过
         */
        private boolean allowed;

        /**
         * 响应的表头
         */
        private Map<String, String> headers;

        public RateLimiterResponse(boolean allowed) {
            this.allowed = allowed;
            this.headers = Collections.emptyMap();
        }

        public RateLimiterResponse(boolean allowed, Map<String, String> headers) {
            this.allowed = allowed;
            Assert.notNull(headers, "headers may not be null");
            this.headers = headers;
        }
    }
}
